package org.jiucheng.magpiebridge.protocol;

import java.nio.ByteBuffer;

public class Message {
    
    public static final int MAGIC = 1314520;
    
    public static final class Type {
        
        /** 认证消息，检测clientKey是否正确 */
        public static final byte AUTH = 0x01;
        
        /** 代理后端服务器建立连接消息 */
        public static final byte CONNECT = 0x03;

        /** 代理后端服务器断开连接消息 */
        public static final byte DISCONNECT = 0x04;

        /** 代理数据传输 */
        public static final byte TRANSFER = 0x05;
        
        /** 心跳消息 */
        public static final byte HEARTBEAT = 0x07;
        
        /** 代理重置*/
        public static final byte PROXYRESET = 0x08;
    }
    
    // 消息头
    // 4字节：MAGIC
    // 1字节：类型
    // 4字节：动态
    // 4字节：消息体长度
    private int magic;
    private byte type;
    private int uri;
    private int size;
    // 消息体
    private byte[] data;
    
    public int getMagic() {
        return magic;
    }

    public void setMagic(int magic) {
        this.magic = magic;
    }
    
    public byte getType() {
        return type;
    }
    
    public void setType(byte type) {
        this.type = type;
    }
    
    public int getUri() {
        return uri;
    }
    
    public void setUri(int uri) {
        this.uri = uri;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public byte[] getData() {
        return data;
    }

    public void setData(byte[] data) {
        this.data = data;
    }
    
    public static Message fromByteBuffer(ByteBuffer byteBuffer) {
        byteBuffer.flip();
        Message message = new Message();
        message.setMagic(byteBuffer.getInt());
        message.setType(byteBuffer.get());
        message.setUri(byteBuffer.getInt());
        message.setSize(byteBuffer.getInt());
        if (message.getSize() > 0) {
            byte[] data = new byte[message.getSize()];
            byteBuffer.get(data);
            message.setData(data);
        }
        return message;
    }
    
    public static ByteBuffer toByteBuffer(Message message) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(message.getSize() + 13);
        byteBuffer.putInt(message.getMagic());
        byteBuffer.put(message.getType());
        byteBuffer.putInt(message.getUri());
        byteBuffer.putInt(message.getSize());
        if (message.getSize() > 0) {
            byteBuffer.put(message.getData());
        }
        byteBuffer.flip();
        return byteBuffer;
    }
}
